import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpService } from 'src/app/service/http.service';
import { AlertController, ModalController, NavController } from '@ionic/angular';
import { ImgModalComponent } from 'src/app/components/img-modal/img-modal.component';
import { TranslateService } from '@ngx-translate/core';
import { ToastService } from '../../../service/toast.service';

@Component({
  selector: 'app-guest-doctorinfo',
  templateUrl: './hospital-info.page.html',
  styleUrls: ['./hospital-info.page.scss'],
})
export class HospitalInfoPage implements OnInit {
  hospitalUserId = 0;
  hospitalUserInfo: any = {};
  orderId = null;
  orderAccept = 0;
  sysLang = '';
  patientUserId = null;
  hasOrder = 0;

  constructor(
    private activatedRoute: ActivatedRoute,
    private httpService: HttpService,
    private alertController: AlertController,
    private router: Router,
    private modalController: ModalController,
    private translate: TranslateService,
    private navController: NavController,
    private toastSrv: ToastService
  ) {
    activatedRoute.queryParams.subscribe(async queryParams => {
      if (!!queryParams.hospitalUserId) {
        this.hospitalUserId = queryParams.hospitalUserId;
        this.patientUserId = queryParams.patientUserId;
        this.orderId = queryParams.orderId;
        this.orderAccept = Number(queryParams.orderAccept);
        await this.getHospitalUserInfo();
      }

      this.hasOrder = Number(queryParams.hasOrder);
      console.log(' this.hasOrder:',  this.hasOrder);
      console.log(' this.orderId:',  this.orderId);
    });
  }

  ngOnInit() {
    this.sysLang = this.translate.getBrowserCultureLang().toLowerCase();
  }

  async ionViewWillLeave() {
    const appointAndLogin = localStorage.getItem('appointAndLogin');
    if (appointAndLogin) {
      localStorage.removeItem('appointAndLogin');
      await this.navController.navigateRoot('/patient-app');
    }
  }

  private async getHospitalUserInfo() {
    const result: any = await this.httpService.get()
      .setPath('/pub/user/hospitalUserInfo/' + this.hospitalUserId)
      .request();
    if (result.status === 0) {
      this.hospitalUserInfo = result.data;
    }
  }

  private async queryPatientAppointOrder() {
    const result: any = await this.httpService.get()
        .setPath('/order/orderInfo')
        .setQuery({
          patientUserId: this.patientUserId,
          orderType: 1,
          bookingType: 2,
          // acceptType: 2
          processAccept: true
        })
        .request();
    if (result.status === 0) {
      return result.data;
    }
  }

  public async appointmentNow() {
    const alertData = {
      'en-us': {
        header: 'Alert',
        message: 'Login/Register to experience more',
        cancelText: 'Cancel',
        okText: 'Next',
        toast: `You can only book one testing at a time.`
      },
      'zh-cn': {
        header: '提示',
        message: '登录/注册后方可体验更多功能',
        cancelText: '取消',
        okText: '立即前往',
        toast: '只能预约一个检测'
      }
    };

    if (this.hospitalUserInfo.order_type === 1) {
      if (this.patientUserId) {
        const patientOrder = await this.queryPatientAppointOrder();
        if (patientOrder) {
          return this.toastSrv.showToast(alertData[this.sysLang].toast);
        }
      }

      await this.router.navigate(['patient-registion-times'], {
        queryParams: { doctorId: this.hospitalUserInfo.id }
      });
    } else {
      const alert = await this.alertController.create({
        header: alertData[this.sysLang].header,
        message: alertData[this.sysLang].message,
        buttons: [
          {
            text: alertData[this.sysLang].cancelText,
            role: 'cancel',
            cssClass: 'secondary',
            handler: (blah) => {
              console.log('Confirm Cancel: blah');
            }
          }, {
            text: alertData[this.sysLang].okText,
            handler: () => {
              this.navController.navigateForward(['login'], {
                queryParams: {}
              });
            }
          }
        ]
      });
      await alert.present();
    }
  }

  public async cancelAppoint() {
    const alertData = {
      'en-us': {
        header: 'Alert',
        message: 'Cancel Appoint?',
        cancelText: 'Close',
        okText: 'Confirm'
      },
      'zh-cn': {
        header: '提示',
        message: '取消预约吗？',
        cancelText: '关闭',
        okText: '确认'
      }
    };

    const cancelAppointAlert = await this.alertController.create({
      header: alertData[this.sysLang].header,
      message: alertData[this.sysLang].message,
      buttons: [
        {
          text: alertData[this.sysLang].cancelText,
          role: 'cancel',
          cssClass: 'secondary',
        },
        {
          text: alertData[this.sysLang].okText,
          handler: async () => {
            const result: any = await this.httpService.put()
                .setPath('/order/reject/' + this.orderId)
                .setBody({
                  rejectType: 2
                })
                .request();
            if (result.status === 0) {
              await this.router.navigate(['/patient-app/patient-my-appointments']);
            }
          }
        }
      ]
    });
    await cancelAppointAlert.present();

    /*const result: any = await this.httpService.put()
        .setPath('/order/reject/' + this.orderId)
        .request();
    if (result.status === 0) {
      await this.router.navigate(['/patient-app/patient-my-appointments']);
    }*/
  }

  public async showPI() {
    const modal = await this.modalController.create({
      component: ImgModalComponent,
      componentProps: {
        title: 'HospitalInfo',
        personalInfo: this.hospitalUserInfo.personal_desc
      }
    });
    await modal.present();
  }

  public async showTestingProject() {
    const modal = await this.modalController.create({
      component: ImgModalComponent,
      componentProps: {
        title: 'TestingProject',
        personalInfo: this.hospitalUserInfo.testing_item
      }
    });
    await modal.present();
  }

  public async showMQ() {
    const modal = await this.modalController.create({
      component: ImgModalComponent,
      componentProps: {
        title: ['MedicalQualifications', 'HospitalQualifications'][this.hospitalUserInfo.type - 2],
        imgId: this.hospitalUserInfo.attachment_url,
        medicalQualification: this.hospitalUserInfo.medical_qualification,
      }
    });
    await modal.present();
    const { data } = await modal.onDidDismiss();
  }

  public async showPH() {
    const modal = await this.modalController.create({
      component: ImgModalComponent,
      componentProps: {
        title: 'PersonalHonors',
        personalRewards: this.hospitalUserInfo.personal_honor
      }
    });
    await modal.present();
  }
}
